package com.hbb20;


import com.futuremind.recyclerviewfastscroll.FastScroller;
import com.futuremind.recyclerviewfastscroll.ImageTint;
import com.hbb20.utils.SystemUtils;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.components.element.VectorElement;
import ohos.agp.utils.LayoutAlignment;
import ohos.app.Context;
import ohos.global.resource.Resource;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

import java.util.List;

/**
 * Created by hbb20 on 11/1/16.
 */
class CountryCodeDialog {

    static MyDialog dialog;
    static Context context;


    public static void openCountryCodeDialog(final CountryCodePicker codePicker) {
        openCountryCodeDialog(codePicker, null);
    }

    public static void
    openCountryCodeDialog(final CountryCodePicker codePicker, final String countryNameCode) {
        context = codePicker.getContext();
        int windowWidth = SystemUtils.getDisplayWidthInPx(context);
        int windowHeight = SystemUtils.getDisplayHightInPx(context);
        Component popLayout = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_layout_picker_dialog, null, true);
        dialog = new MyDialog(context);

        dialog.setContentCustomComponent(popLayout);
        dialog.setSize(windowWidth - 80, windowHeight - 120);
        codePicker.refreshCustomMasterList();
        codePicker.refreshPreferredCountries();
        List<CCPCountry> masterCountries = CCPCountry.getCustomMasterCountryList(context, codePicker);

        //dialog views
        ListContainer recyclerView_countryDialog = (ListContainer) popLayout.findComponentById(ResourceTable.Id_recycler_countryDialog);
        final Text textViewTitle = (Text) popLayout.findComponentById(ResourceTable.Id_textView_title);
        DependentLayout rlQueryHolder = (DependentLayout) popLayout.findComponentById(ResourceTable.Id_rl_query_holder);
        Image imgClearQuery = (Image) popLayout.findComponentById(ResourceTable.Id_img_clear_query);
        final TextField editText_search = (TextField) popLayout.findComponentById(ResourceTable.Id_editText_search);
        Text textView_noResult = (Text) popLayout.findComponentById(ResourceTable.Id_textView_noresult);
        DirectionalLayout dialogRoot = (DirectionalLayout) popLayout.findComponentById(ResourceTable.Id_cardViewRoot);
        Image imgDismiss = (Image) popLayout.findComponentById(ResourceTable.Id_img_dismiss);
        Component line2 = popLayout.findComponentById(ResourceTable.Id_component_line);
        FocusLine.drawFocusLine(editText_search, line2);


        // type faces
        //set type faces
        try {
            if (codePicker.getDialogTypeFace() != null) {
                textView_noResult.setFont(codePicker.getDialogTypeFace());
                editText_search.setFont(codePicker.getDialogTypeFace());
                textViewTitle.setFont(codePicker.getDialogTypeFace());
            }
        } catch (Exception e) {
        }

        //dialog background color
        //
        if (codePicker.getDialogBackgroundColor() != 0) {
            ShapeElement shapeElement = new ShapeElement();
            shapeElement.setCornerRadius(codePicker.getDialogCornerRadius());
            shapeElement.setRgbColor(RgbColor.fromArgbInt(codePicker.getDialogBackgroundColor()));
            dialogRoot.setBackground(shapeElement);
        }

        // gradient 用java 代码实现
        if (codePicker.getBackgroundGradientColors() != null) {
            ShapeElement shapeElement = new ShapeElement();
            shapeElement.setCornerRadius(codePicker.getDialogCornerRadius());
            shapeElement.setRgbColors(codePicker.getBackgroundGradientColors());
            String backgroundGradientOrientation = codePicker.getBackgroundGradientOrientation();
            ShapeElement.Orientation orientation = ShapeElement.Orientation.valueOf(backgroundGradientOrientation);
            shapeElement.setGradientOrientation(orientation);
            dialogRoot.setBackground(shapeElement);
        }

        if (codePicker.getDialogBackground() != null) {
            dialogRoot.setBackground(codePicker.getDialogBackground());
        }
        dialog.setCornerRadius(codePicker.getDialogCornerRadius());
        //close button visibility
        if (codePicker.isShowCloseIcon()) {
            imgDismiss.setVisibility(Component.VISIBLE);
            imgDismiss.setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {
                    dialog.destroy();
                }
            });
        } else {
            imgDismiss.setVisibility(Component.HIDE);
        }

        //title
        if (!codePicker.getCcpDialogShowTitle()) {
            textViewTitle.setVisibility(Component.HIDE);
        }

        //clear button color and title color
        if (codePicker.getDialogTextColor() != 0) {
            int textColor = codePicker.getDialogTextColor();
            VectorElement vectorElement = new VectorElement(context, ResourceTable.Graphic_ic_backspace_black_24dp);
            ImageTint.setImageTint(imgClearQuery, vectorElement, textColor);

            try {
                Resource imageResource = context.getResourceManager().getResource(ResourceTable.Media_ic_clear_black);
                PixelMap pixelmap = ImageSource.create(imageResource, null).createPixelmap(null);
                PixelMapElement pixelMapElement = new PixelMapElement(pixelmap);
                ImageTint.setImageTint(imgDismiss, pixelMapElement, textColor);
            } catch (Exception e) {
            }

            ohos.agp.utils.Color color = new ohos.agp.utils.Color(textColor);
            textViewTitle.setTextColor(color);
            textView_noResult.setTextColor(color);
            editText_search.setTextColor(color);
            RgbColor rgbColor = RgbColor.fromArgbInt(textColor);
            int argb = ohos.agp.utils.Color.argb(100, rgbColor.getRed(), rgbColor.getGreen(), rgbColor.getBlue());
            editText_search.setHintColor(new ohos.agp.utils.Color(argb));
        }
        //editText tint
        if (codePicker.getDialogSearchEditTextTintColor() != 0) {
            setCursorColor(editText_search, codePicker.getDialogSearchEditTextTintColor());
        }


        //add messages to views
        textViewTitle.setText(codePicker.getDialogTitle());
        editText_search.setHint(codePicker.getSearchHintText());
        textView_noResult.setText(codePicker.getNoResultACK());

        //this will make dialog compact
        if (!codePicker.isSearchAllowed()) {
            DependentLayout.LayoutConfig params = (DependentLayout.LayoutConfig) recyclerView_countryDialog.getLayoutConfig();
            params.height = DependentLayout.LayoutConfig.MATCH_CONTENT;
            recyclerView_countryDialog.setLayoutConfig(params);
        }
        final CountryCodeAdapter cca = new CountryCodeAdapter(context, masterCountries, codePicker, rlQueryHolder, editText_search, textView_noResult, dialog, imgClearQuery);
        recyclerView_countryDialog.setItemProvider(cca);
        //fast scroller
        FastScroller fastScroller = (FastScroller) popLayout.findComponentById(ResourceTable.Id_fastscroll);
        fastScroller.setRecyclerView(recyclerView_countryDialog);
        if (codePicker.isShowFastScroller()) {
            if (codePicker.getFastScrollerBubbleColor() != 0) {
                fastScroller.setBubbleColor(codePicker.getFastScrollerBubbleColor());
            }
            if (codePicker.getFastScrollerHandleColor() != 0) {
                fastScroller.setHandleColor(codePicker.getFastScrollerHandleColor());
            }
            if (codePicker.getFastScrollerBubbleTextAppearance() != 0) {
                try {
                    fastScroller.setBubbleTextAppearance(codePicker.getFastScrollerBubbleTextAppearance());
                } catch (Exception e) {
                }
            }
        } else {
            fastScroller.setVisibility(Component.HIDE);
        }

        dialog.setKeyboardListener((show, height) -> {
            cca.notifyDataChanged();
        });

        dialog.setOnDismissListener(dialog -> {
            hideSoftInput(editText_search);
            if (codePicker.getDialogEventsListener() != null) {
                codePicker.getDialogEventsListener().onCcpDialogDismiss(dialog);
            }
        });


        //auto scroll to mentioned countryNameCode
        if (countryNameCode != null) {
            boolean isPreferredCountry = false;
            if (codePicker.preferredCountries != null) {
                for (CCPCountry preferredCountry : codePicker.preferredCountries) {
                    if (preferredCountry.nameCode.equalsIgnoreCase(countryNameCode)) {
                        isPreferredCountry = true;
                        break;
                    }
                }
            }

            //if selection is from preferred countries then it should show all (or maximum) preferred countries.
            // don't scroll if it was one of those preferred countries
            if (!isPreferredCountry) {
                int preferredCountriesOffset = 0;
                if (codePicker.preferredCountries != null && codePicker.preferredCountries.size() > 0) {
                    preferredCountriesOffset = codePicker.preferredCountries.size() + 1; //+1 is for divider
                }
                for (int i = 0; i < masterCountries.size(); i++) {
                    if (masterCountries.get(i).nameCode.equalsIgnoreCase(countryNameCode)) {
                        // recyclerView_countryDialog.scrollToPosition(i + preferredCountriesOffset);
                        recyclerView_countryDialog.scrollTo(i + preferredCountriesOffset);
                        break;
                    }
                }
            }
        }

        dialog.setAlignment(LayoutAlignment.CENTER);
        dialog.show();
        if (codePicker.getDialogEventsListener() != null) {
            codePicker.getDialogEventsListener().onCcpDialogOpen(dialog);
        }
    }


    private static void hideSoftInput(TextField editText) {
        if (editText != null) {
            editText.clearFocus();
        }
    }

    private static void setCursorColor(TextField editText, int color) {
        ShapeElement shapeElement = new ShapeElement();
        shapeElement.setRgbColor(RgbColor.fromArgbInt(color));
        editText.setCursorElement(shapeElement);
    }

    static void clear() {
        if (dialog != null) {
            try {
                dialog.destroy();
            } catch (Exception e) {
            }
        }
        dialog = null;
        context = null;
    }

}
